package com.weetop.akly.activity.work;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.weetop.akly.R;
import com.weetop.akly.base.BaseActivity;
import com.weetop.akly.base.mvp.BaseModel;
import com.weetop.akly.bean.ApproveItem;
import com.weetop.akly.bean.BaseCountBean;
import com.weetop.akly.bean.DaySignBean;
import com.weetop.akly.bean.SignResultBean;
import com.weetop.akly.bean.WorkGroupBean;
import com.weetop.akly.bean.WorkLogResultBean;
import com.weetop.akly.presenter.SignPresent;
import com.weetop.akly.utils.BaseUtils;
import com.weetop.akly.utils.EquipmentUtil;
import com.weetop.akly.utils.LocalUtil;
import com.weetop.akly.utils.MacUtil;
import com.weetop.akly.utils.TimeUtils;
import com.weetop.akly.utils.widget.AlertDialogIOS;
import com.weetop.akly.view.SignView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 打卡签到
 */
public class WorkDaySignActivity extends BaseActivity<SignPresent> implements SignView {

    @BindView(R.id.tv_groupName)
    TextView tvGroupName;
    @BindView(R.id.rl_chooseGroup)
    RelativeLayout rlChooseGroup;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_banci_title)
    TextView tvBanciTitle;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.rl_sign)
    RelativeLayout rlSign;
    @BindView(R.id.rcy_data)
    RecyclerView rcyData;
    @BindView(R.id.tv_sign_text)
    TextView tvSignText;
    @BindView(R.id.tv_sign_attime)
    TextView tvSignAttime;
    @BindView(R.id.ll_sign)
    LinearLayout llSign;
    private QMUIBottomSheet chooseGroupSheet;
    private String mGroupId;
    private String group_classid;
    private CommonRecyclerAdapter<DaySignBean> logAdapter;

    private ArrayList<DaySignBean> daySignBeanList = new ArrayList<>();
    private ArrayList<WorkLogResultBean.LogBean> loglist = new ArrayList<>();
    private double latitude, longitude;
    private String wifiName = "";
    private String wifiMacAddress = "";
    private String mAddress = "";

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(runnable, 1000);
            //计算当前时间
            culCurrentTime();
        }
    };
    private LocalUtil localUtil;
    private int MY_PERMISSIONS_REQUEST_LOCATION = 10000;
    private AlertDialogIOS myDialog;

    @Override
    protected SignPresent createPresenter() {
        return new SignPresent(this, this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_day_sign);
        ButterKnife.bind(this);
        setTitleInfo("打卡");
        if (myApplication.getAccountInfoBean() != null) {
            tvName.setText(myApplication.getAccountInfoBean().getInfo().getName() + "  考勤班次：");
        }

        initData();
        //请求考勤组列表
        mPresenter.getWorkGroupList();
        initAletDialog();
    }

    private void initAletDialog() {
        myDialog = new AlertDialogIOS(this).builder();
    }

    private void initData() {
        String date = BaseUtils.getTimeFormat(System.currentTimeMillis() + "", "yyyy.MM.dd");
        tvTime.setText(date);
        //立即调用该方法
        handler.post(runnable);
        wifiMacAddress = MacUtil.getMac();
        wifiName = MacUtil.getConnectWifiSsid(this);
        //检查权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //如果当前系统是大于23的话
            if (PermissionUtils.isGranted(PermissionConstants.LOCATION)) {
                //用户已经授权
                getLoation();
            } else {
                //请求授权 系统会打开弹窗
                PermissionUtils.permission(PermissionConstants.LOCATION)
                        .callback(new PermissionUtils.FullCallback() {
                            @Override
                            public void onGranted(List<String> permissionsGranted) {
                                getLoation();
                            }

                            @Override
                            public void onDenied(List<String> permissionsDeniedForever,
                                                 List<String> permissionsDenied) {
                                if (!permissionsDeniedForever.isEmpty()) {
//                                    PermissionHelper.showOpenAppSettingDialog();
                                }
                                LogUtils.d(permissionsDeniedForever, permissionsDenied);
                            }
                        })
                        .theme(new PermissionUtils.ThemeCallback() {
                            @Override
                            public void onActivityCreate(Activity activity) {
                                ScreenUtils.setFullScreen(activity);
                            }
                        })
                        .request();
            }
        } else {
            getLoation();
        }

        rcyData.setItemAnimator(null);
        logAdapter = new CommonRecyclerAdapter<DaySignBean>(mContext, R.layout.item_log, daySignBeanList) {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onUpdate(BaseAdapterHelper helper, DaySignBean item, int position) {
                helper.setText(R.id.tv_data, item.getTimes());
                helper.setText(R.id.tv_recored, "打卡记录：" + item.getTimes());

                TextView tv_info = helper.getView(R.id.tv_info);
                TextView tv_status = helper.getView(R.id.tv_status);
                View viewTopLine = helper.getView(R.id.view_topline);
                View viewBottomLine = helper.getView(R.id.view_bottomline);
                View viewDividerLine = helper.getView(R.id.view_divider_line);
                View btnRefreshKa = helper.getView(R.id.btn_refreshka);
                TextView btn_buka = helper.getView(R.id.btn_buka);

                if (position % 2 == 0) {
                    tv_status.setText("上班打卡");
                    if (position == daySignBeanList.size() - 1) {
                        viewTopLine.setVisibility(View.GONE);
                        viewBottomLine.setVisibility(View.GONE);
                    } else {
                        viewTopLine.setVisibility(View.GONE);
                        viewBottomLine.setVisibility(View.VISIBLE);
                    }
                } else {
                    tv_status.setText("下班打卡");
                    viewTopLine.setVisibility(View.VISIBLE);
                    viewBottomLine.setVisibility(View.GONE);
                }
//
//                if (position == daySignBeanList.size() - 1) {
//                    viewDividerLine.setVisibility(View.GONE);
//                    btnRefreshKa.setVisibility(View.VISIBLE);
//                } else {
//                    viewDividerLine.setVisibility(View.VISIBLE);
//                    btnRefreshKa.setVisibility(View.GONE);
//                }

                btn_buka.setVisibility(View.VISIBLE);
                switch (item.getStatus()) {
                    //1正常，2外勤，3迟到，4早退，5旷工，6请假，7外出，8休息，9缺卡
                    case 1:
                        tv_info.setText("正常");
                        btn_buka.setVisibility(View.GONE);
                        tv_info.setBackgroundResource(R.color.sign_1);
                        break;
                    case 2:
                        tv_info.setText("外勤");
                        tv_info.setBackgroundResource(R.color.sign_2);
                        break;
                    case 3:
                        tv_info.setText("迟到");
                        tv_info.setBackgroundResource(R.color.sign_3);
                        break;
                    case 4:
                        tv_info.setText("早退");
                        tv_info.setBackgroundResource(R.color.sign_4);
                        break;
                    case 5:
                        tv_info.setText("旷工");
                        tv_info.setBackgroundResource(R.color.sign_5);
                        break;
                    case 6:
                        tv_info.setText("请假");
                        tv_info.setBackgroundResource(R.color.sign_3);
                        break;
                    case 7:
                        tv_info.setText("外出");
                        tv_info.setBackgroundResource(R.color.sign_3);
                        break;
                    case 8:
                        tv_info.setText("休息");
                        tv_info.setBackgroundResource(R.color.sign_3);
                        break;
                    default:
                        tv_info.setText("缺省");
                        tv_info.setBackgroundResource(R.color.day_signed);
                        break;
                }
                // 补卡点击事件
                helper.setOnClickListener(R.id.btn_buka, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.putExtra("kaoqin_id", item.getId() + "");
                        intent.putExtra("status", item.getStatus() + "");
                        BaseUtils.toActivity(mActivity, SignOutActivity.class, intent);
                    }
                });
                //重新打卡点击事件
                helper.setOnClickListener(R.id.btn_refreshka, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        checkIn(item.getId() + "");
                    }
                });

            }
        };
        rcyData.setAdapter(logAdapter);
    }

    private void getLoation() {
        if (localUtil == null) {
            localUtil = new LocalUtil(getApplicationContext());
        }
        localUtil.startLocation(new LocalUtil.MyLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                int errorCode = location.getLocType();
//                    if (errorCode)
                latitude = location.getLatitude();    //获取纬度信息
                longitude = location.getLongitude();    //获取经度信息
                mAddress = location.getAddrStr();    //获取详细地址信息
            }
        });
    }


    private void culCurrentTime() {
        String time = BaseUtils.getTimeFormat(System.currentTimeMillis() + "", "HH:mm:ss");
        tvSignAttime.setText(time);
    }

    public void overTimeList() {
        HashMap<String, String> map = new HashMap<>();
        map.put("type", "1");
        map.put("start_day", TimeUtils.fromLongToDate("yyyy-MM-dd", System.currentTimeMillis()));
        map.put("status", "1");
        mPresenter.overTimeList(map);
    }

    @Override
    public void overTimeListSuccess(BaseModel<BaseCountBean<ApproveItem>> o) {
        if (o.getData() == null || o.getData().getList_data() == null || o.getData().getList_data().isEmpty()) {
            myDialog.setGone().setTitle("提示").setMsg("确定进行打卡操作？").setNegativeButton("取消", null).setPositiveButton("确定", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    checkIn(null);
                }
            }).show();
        } else {
            long endTime = com.blankj.utilcode.util.TimeUtils.string2Millis(o.getData().getList_data().get(0).getEnd_time());
            if (endTime > System.currentTimeMillis()) {
                myDialog.setGone().setTitle("提示").setMsg("您有加班任务，未到下班时间点，确认打卡吗？").setNegativeButton("取消", null).setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        checkIn(null);
                    }
                }).show();
            }
        }
    }

    /**
     * 获取考勤组列表成功
     *
     * @param o
     */
    @Override
    public void getWorkGroupListSuccess(BaseModel<ArrayList<WorkGroupBean>> o) {
        //默认选择第一个考勤组
        ArrayList<WorkGroupBean> groupBeanArrayList = o.getData();
        mGroupId = groupBeanArrayList.get(0).getGroup_id() + "";
        tvGroupName.setText(groupBeanArrayList.get(0).getGroup_name());
        mPresenter.getWorkLogList(mGroupId);
        //初始化考勤组弹窗
//        QMUIBottomSheet.BottomListSheetBuilder chooseHeadImgBottomSheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(this);
//        for (WorkGroupBean datum : groupBeanArrayList) {
//            chooseHeadImgBottomSheetBuilder.addItem(datum.getGroup_name(), datum.getGroup_id() + "");
//        }
//        chooseHeadImgBottomSheetBuilder.setOnSheetItemClickListener((dialog, itemView, position, tag) -> {
//            tvGroupName.setText(groupBeanArrayList.get(position).getGroup_name());
//            mGroupId = tag;
//            mPresenter.getWorkLogList(mGroupId);
//            dialog.dismiss();
//        });
//        chooseGroupSheet = chooseHeadImgBottomSheetBuilder.build();
    }

    @Override
    public void getWorkLogListSuccess(BaseModel<WorkLogResultBean> o) {
        group_classid = o.getData().getInfo().getId() + "";
        tvBanciTitle.setText(o.getData().getInfo().getName());
        //加载日志
        loglist.clear();
        loglist.addAll(o.getData().getLog());
        mPresenter.getDayCheckinWatch(TimeUtils.fromLongToDate("yyyy-MM-dd", System.currentTimeMillis()));
    }

    /**
     * 签到成功 /更新打卡成功
     *
     * @param
     */
    @Override
    public void workSignSuccess() {
        mPresenter.getWorkLogList(mGroupId);
    }

    @Override
    public void getDayCheckinWatchSuccess(BaseModel<ArrayList<DaySignBean>> o) {
        if (o.getData().size() == 0) {
            llSign.setVisibility(View.VISIBLE);
            tvSignText.setText("上班打卡");
        } else if (o.getData().size() == 1) {
            llSign.setVisibility(View.VISIBLE);
            tvSignText.setText("下班打卡");
        } else {
            llSign.setVisibility(View.GONE);
        }
        daySignBeanList.clear();
        daySignBeanList.addAll(o.getData());
        logAdapter.replaceAll(o.getData());
    }

    @OnClick({R.id.rl_chooseGroup, R.id.rl_sign})
    public void onViewClicked(View view) {
        if (BaseUtils.fastClick())
            switch (view.getId()) {
                case R.id.rl_chooseGroup:
//                    chooseGroupSheet.show();
                    break;
                case R.id.rl_sign:
                    if (daySignBeanList.size() == 1) {
                        overTimeList();
                    } else {
                        myDialog.setGone().setTitle("提示").setMsg("确定进行打卡操作？").setNegativeButton("取消", null).setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                checkIn(null);


                            }
                        }).show();
                    }
                    break;
            }
    }

    private void checkIn(String update_id) {
        if (latitude != 0 && mGroupId != null && group_classid != null) {
            Map<String, String> map = new HashMap<>();
            map.put("group_id", mGroupId);
            map.put("group_class", group_classid);
            map.put("wifi_name", wifiName);
            map.put("wifi_mac", wifiMacAddress);

            map.put("phone_name", EquipmentUtil.getSystemDevice());
            map.put("phone_imei", EquipmentUtil.getIMEI(this));
            map.put("phone_mac", wifiMacAddress);

            map.put("location_lng", longitude + "");
            map.put("location_lat", latitude + "");
            map.put("location_ad", mAddress);
            map.put("update_id", TextUtils.isEmpty(update_id) ? "0" : update_id);
//            map.put("port_type", "1");

            mPresenter.toSign(map);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacks(runnable);
            handler = null;
        }
        if (localUtil != null) {
            localUtil.stopLocal();
        }
    }
}
